<template>
  <el-row class="mx__20 px-20 bg-white">
    <el-col class="current-content-style">
      <el-row class="py-20">
        <el-col>
          <el-row type="flex" justify="left" :gutter="0">
            <el-select v-model="searchNoticeState" placeholder="选择发布状态" class="mr-20">
              <!-- <el-option value="" label="请选择" disabled></el-option> -->
              <el-option v-if="userRoleId === 1 || userRoleId === 2" :value="1" label="未发布"></el-option>
              <el-option :value="2" label="已发布"></el-option>
            </el-select>
            <el-input class="mr-20" v-model.trim="searchValue" placeholder="按标题搜索" style="width: 200px"></el-input>
            <el-button type="primary" plain @click="searchHandler">查询</el-button>
            <el-button v-if="userRoleId === 2 || userRoleId === 1" plain type="success" @click="showAddNotice"
              >新增通知</el-button
            >
          </el-row>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-table
            stripe
            :data="tableData"
            style="width: 100%"
            :header-row-class-name="
              ({ row, rowIndex }) => {
                if (rowIndex === 0) return 'table-header-bg'
              }
            "
          >
            <el-table-column prop="noticeTitle" label="标题"> </el-table-column>
            <el-table-column prop="noticeContent" label="内容"> </el-table-column>
            <el-table-column prop="adminName" label="发布人"> </el-table-column>
            <el-table-column label="发布状态">
              <template v-slot="scope">
                <span :class="scope.row.noticeState === 1 ? 'text-warning' : 'text-success'">
                  {{ scope.row.noticeState === 1 ? '未发布' : '已发布' }}</span
                >
              </template>
            </el-table-column>
            <el-table-column prop="noticePublishTime" label="发布时间"> </el-table-column>
            <el-table-column prop="money" label="操作">
              <template v-slot="scope">
                <i class="text-20 curser-pointer text-primary mr-20 el-icon-s-comment" @click="showInfo(scope.row)"></i>
                <i
                  v-if="userRoleId === 1 || userRoleId === 2"
                  class="text-20 curser-pointer text-danger mr-20 el-icon-delete"
                  @click="deleteNotice(scope.row.noticeId)"
                ></i>
                <i
                  v-if="userRoleId === 1 || userRoleId === 2"
                  class="text-20 curser-pointer text-warning mr-20 el-icon-edit"
                  @click="showInfo(scope.row, 'edit')"
                ></i>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-dialog :title="modalTitle" :visible.sync="infoModal" width="30%">
        <el-row>
          <el-col>
            <el-form ref="editInfoForm" :model="infoForm" :rules="infoFormRules" :disabled="modalTitle !== '编辑公告'">
              <el-form-item label="公告标题" prop="noticeTitle">
                <el-input v-model="infoForm.noticeTitle"></el-input>
              </el-form-item>
              <el-form-item label="公告内容" prop="noticeContent">
                <el-input type="textarea" v-model="infoForm.noticeContent"></el-input>
              </el-form-item>
              <el-form-item label="公告状态" prop="noticeState">
                <el-radio-group v-model="infoForm.noticeState">
                  <el-radio :label="1">未发布</el-radio>
                  <el-radio :label="2">已发布</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button v-if="modalTitle !== '编辑公告'" type="primary" @click="infoModal = false">确定</el-button>
          <el-button v-else type="primary" @click="editNoticeHandler">修改</el-button>
        </span>
      </el-dialog>

      <el-dialog title="新增公告" :visible.sync="addModal" width="30%">
        <el-row>
          <el-col>
            <el-form ref="addform" :model="addForm" :rules="addFormRules" label-width="60px">
              <el-form-item label="标题" prop="noticeTitle">
                <el-input v-model.number="addForm.noticeTitle" type="text" placeholder="通知、公告标题"> </el-input>
              </el-form-item>
              <el-form-item label="内容" prop="noticeContent">
                <el-input v-model.number="addForm.noticeContent" type="textarea" placeholder="详细内容"> </el-input>
              </el-form-item>
              <el-form-item label="状态" prop="noticeState">
                <el-select v-model="addForm.noticeState">
                  <el-option :value="1" label="未发布"></el-option>
                  <el-option :value="2" label="已发布"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addModal = false">取消</el-button>

          <el-button type="primary" @click="addNoticeHandler('addform')">确定</el-button>
        </span>
      </el-dialog>
      <el-row class="my-20" style="text-align: right">
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
// 通知公告
import {
  waterNoticeAdd,
  waterNoticeDelete,
  // waterNoticeQuery,
  waterNoticeQueryPage,
  waterNoticeUpdate
} from '@/config/api'
import { checkZero } from '@/utils/dateUtils'
export default {
  data() {
    return {
      userRoleId: undefined, //角色ID
      infoModal: false,
      addModal: false,
      addForm: { noticeTitle: '', noticeContent: '', noticeState: 1 },
      addFormRules: {
        noticeTitle: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        noticeContent: [
          { required: true, message: '请输内容', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        noticeState: [{ required: true, message: '请输选择状态', trigger: 'change' }]
      },
      infoForm: { noticeTitle: '', noticeContent: '', noticeState: 1 },
      infoFormRules: {
        noticeTitle: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'change' }
        ],
        noticeContent: [
          { required: true, message: '请输内容', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'change' }
        ],
        noticeState: [{ required: true, message: '请输选择状态', trigger: 'change' }]
      },
      pageSizes: [5, 10, 15, 20],
      pageSize: 5,
      total: 0,
      currentPage: 1,
      searchValue: '', // 标题
      tableData: [],
      isSearch: false, // 是否搜索
      searchNoticeState: '', // 发布状态，
      userId: this.$store.state.userInfo.adminId, // 当前用户id
      modalTitle: '' // 查看，编辑公告的模态框标题
    }
  },
  created() {
    this.waterNoticeQueryPageHandler()
    this.userRoleId = this.$store.state.userInfo.roleId
  },
  methods: {
    // 生成发布公告的日期字符串
    getUserFormatDate() {
      let d = new Date()
      let y = d.getFullYear()
      let m = d.getMonth()
      let date = d.getDay()
      let h = d.getHours()
      let m2 = d.getMinutes()
      let s = d.getSeconds()
      return (
        y + '-' + checkZero(m) + '-' + checkZero(date) + ' ' + checkZero(h) + ':' + checkZero(m2) + ':' + checkZero(s)
      )
    },

    // 删除公告
    deleteNotice(id) {
      id = Number(id)
      waterNoticeDelete({ noticeId: id }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '删除公告成功',
            type: 'success'
          })
          this.waterNoticeQueryPageHandler()
        } else {
          this.$message({
            message: '删除公告失败',
            type: 'error'
          })
        }
      })
    },
    // 查询
    searchHandler() {
      let params = {
        pageSize: this.pageSize,
        pageNum: this.currentPage
        // noticeState: this.searchNoticeState,
        // noticeTitle: this.searchValue
      }
      this.searchNoticeState && (params.noticeState = Number(this.searchNoticeState))
      this.searchValue && (params.noticeTitle = this.searchValue)
      waterNoticeQueryPage(params).then(res => {
        console.log('search’s Value:', res)

        if (res.code === 200) {
          let arr = res.data.list
          let tempArr = []
          arr.forEach(el => {
            let obj = { ...el.admin }
            let newItem = { ...el, ...obj }
            delete newItem.admin
            tempArr.push(newItem)
          })
          console.log(tempArr)

          // 过滤调未发布的信息
          if (this.userRoleId !== 1 && this.userRoleId !== 2) {
            this.tableData = tempArr.filter(el => el.noticeState === 2)
          } else {
            this.tableData = tempArr
          }
          this.isSearch = true
          // this.tableData = tempArr
          this.total = res.data.total
        } else {
          this.$message({
            message: '请求接口失败',
            type: 'error'
          })
        }
      })
    },
    // 显示添加Modal
    showAddNotice() {
      this.addForm = { noticeTitle: '', noticeContent: '', noticeState: 1 } // 重置
      this.addModal = true
    },
    // 添加
    addNoticeHandler(formName) {
      this.$refs[formName].validate(value => {
        if (value) {
          // 添加
          let params = { ...this.addForm }
          params.adminId = this.userId
          params.noticePublishTime = this.getUserFormatDate()
          // params.noticePublishTime = new Date().getTime()

          waterNoticeAdd(params).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '添加公告成功',
                type: 'success'
              })
              this.addModal = false
              this.waterNoticeQueryPageHandler()
            } else {
              this.$message({
                message: '添加公告失败',
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 显示公告（查看，编辑）的模态框
    showInfo(row, str) {
      // console.log(row)
      this.infoModal = true
      this.infoForm = { ...row } //解构赋值，避免修改内容后，不确定修改时，表格在变化
      if (str === 'edit') {
        this.modalTitle = '编辑公告'
      } else {
        this.modalTitle = '公告信息'
      }
    },
    // 编辑公告
    editNoticeHandler() {
      this.$refs.editInfoForm.validate(value => {
        if (value) {
          waterNoticeUpdate(this.infoForm).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.infoModal = false
              this.waterNoticeQueryPageHandler()
            } else {
              this.$message({
                message: '编辑失败',
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    // 分页，每页条数改变
    handleSizeChange(size) {
      this.pageSize = size
      if (this.isSearch) {
        this.searchHandler()
      } else {
        this.waterNoticeQueryPageHandler()
      }
    },
    // 分页，页面改变
    handleCurrentChange(page) {
      this.currentPage = page
      if (this.isSearch) {
        this.searchHandler()
      } else {
        this.waterNoticeQueryPageHandler()
      }
    },
    // 分页查询公告
    waterNoticeQueryPageHandler() {
      waterNoticeQueryPage({ pageNum: this.currentPage, pageSize: this.pageSize }).then(res => {
        console.log(res)
        if (res.code === 200) {
          let arr = res.data.list
          let tempArr = []
          arr.forEach(el => {
            let obj = { ...el.admin }
            let newItem = { ...el, ...obj }
            delete newItem.admin
            tempArr.push(newItem)
          })
          // 过滤调未发布的信息

          if (this.userRoleId !== 1 && this.userRoleId !== 2) {
            this.tableData = tempArr.filter(el => el.noticeState === 2)
          } else {
            this.tableData = tempArr
          }

          this.total = res.data.total
        } else {
          this.$message({
            message: '请求接口失败',
            type: 'error'
          })
        }
      })
    }
  }
}
</script>

<style scoped>
/* /deep/ .table-header-bg > th {
  background-color: rgba(233, 182, 226, 0.534) !important;
} */
</style>
